package com.ruoyi.financial.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.financial.domain.FEnter;
import com.ruoyi.financial.domain.FOutbound;
import com.ruoyi.financial.domain.FThing;
import com.ruoyi.financial.domain.FThingType;
import com.ruoyi.financial.service.IFEnterService;
import com.ruoyi.financial.service.IFOutboundService;
import com.ruoyi.financial.service.IFThingService;
import com.ruoyi.financial.service.IFThingTypeService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 出库管理Controller
 * 
 * @author xunzhe
 * @date 2024-01-31
 */
@Controller
@RequestMapping("/financial/fOutbound")
public class FOutboundController extends BaseController
{
    private String prefix = "financial/fOutbound";

    @Autowired
    private IFOutboundService fOutboundService;

    @Autowired
    private IFThingService fThingService;

    @Autowired
    private IFThingTypeService fThingTypeService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IFEnterService fEnterService;

    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("financial:fOutbound:view")
    @GetMapping()
    public String fOutbound(ModelMap mmap)
    {
        return prefix + "/fOutbound";
    }

    /**
     * 查询出库管理列表
     */
    @RequiresPermissions("financial:fOutbound:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FOutbound fOutbound)
    {
        startPage();
        List<FOutbound> list = fOutboundService.selectFOutboundList(fOutbound);
        return getDataTable(list);
    }

    /**
     * 导出出库管理列表---入库和出库
     */
    @RequiresPermissions("financial:fOutbound:export")
    @Log(title = "出库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export2")
    @ResponseBody
    public AjaxResult export2(FOutbound fOutbound){
        return null;
    }


    /**
     * 导出出库管理列表-总表
     */
    @RequiresPermissions("financial:fOutbound:export")
    @Log(title = "出库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FOutbound fOutbound)
    {
        List<FOutbound> list = fOutboundService.selectFOutboundList(fOutbound);
        for(FOutbound data : list){
            if(data.getEnterInfo()!=null && !data.getEnterInfo().equals("")){
                String[] split = data.getEnterInfo().split("\\|");
                if(split.length > 0){
                    data.setPinpai(split[0]);
                }
                if(split.length > 1){
                    data.setXinghao(split[1]);
                }
                if(split.length > 2){
                    data.setGuige(split[2]);
                }
            }
        }
        ExcelUtil<FOutbound> util = new ExcelUtil<FOutbound>(FOutbound.class);

        String title = "";
        if(fOutbound.getDeptId()!=null && list.size()>0){
            title = list.get(0).getDeptName();
        }
        if(fOutbound.getParams()!=null && fOutbound.getParams().get("thingId")!=null && !fOutbound.getParams().get("thingId").toString().equals("") && list.size()>0){
            FThing thing = fThingService.selectFThingByThingId(Long.parseLong(fOutbound.getParams().get("thingId").toString()));
            title = title + thing.getThingName();

        }
        if(fOutbound.getThingTypeId()!=null && list.size()>0){
            FThingType fThingType = fThingTypeService.selectFThingTypeByTypeId(fOutbound.getThingTypeId());
            title = title + fThingType.getTypeName();
        }

        return util.exportExcel(list, "出库记录",title);
    }

    /**
     * 新增出库管理
     */
//    @GetMapping("/add")
//    public String add(ModelMap mmap)
//    {
//        mmap.put("peopleNumber",renshu(getSysUser().getDeptId()));
//        return prefix + "/add";
//    }

    @GetMapping("/add")
    public String add(Long enterId,Integer kuncunSize,ModelMap mmap)
    {
        FEnter enter = fEnterService.selectFEnterByEnterId(enterId);
        String enterInfo = enter.getPinpai()+"|"+enter.getXinghao()+"|"+enter.getGuige();
        mmap.put("enter",enter);
        mmap.put("enterInfo",enterInfo);
        mmap.put("kuncunSize",kuncunSize);
        mmap.put("peopleNumber",renshu(getSysUser().getDeptId()));
        return prefix + "/add2";
    }

    public String renshu(){
        List<SysPost> sysPosts = postService.selectPostsByUserId(getSysUser().getUserId());
        List<Map<String, String>> mapList = postService.selectPostsPeople(getSysUser().getDeptId());
        String peopleNumber = "";
        for(Map<String, String> map : mapList){
            Long postId = Long.parseLong(String.valueOf(map.get("post_id")));
            for(SysPost post : sysPosts){
                if(postId.longValue() == post.getPostId().longValue() && post.isFlag()){
                    peopleNumber = Integer.parseInt(String.valueOf(map.get("people_number")))+"";
                    break;
                }
            }
        }
        return peopleNumber;
    }

    public String renshu(Long deptId){
        if(deptId == null){
            return "";
        }
        SysDept sysDept = deptService.selectDeptById(deptId);
        if(sysDept.getTotalPeople() !=null && !sysDept.getTotalPeople().equals("0")){
            return sysDept.getTotalPeople();
        }

        return "";
    }

    /**
     * 新增保存出库管理
     */
    @RequiresPermissions("financial:fOutbound:add")
    @Log(title = "出库管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FOutbound fOutbound)
    {
        fOutbound.setCreateBy(getLoginName());
        fOutbound.setDeptId(getSysUser().getDeptId());

        List<SysPost> sysPosts = postService.selectPostsByUserId(getSysUser().getUserId());
        for(SysPost post : sysPosts){
            if(post.isFlag()){
                fOutbound.setPostId(post.getPostId());
            }
        }
        String sunhao = fOutboundService.selectAverageSunhao(fOutbound);
        fOutbound.setAverageSunhao(sunhao);
        if(fOutbound.getRecipientBy()==null || fOutbound.getRecipientBy().equals("")){
            fOutbound.setRecipientBy(getLoginName());
        }

        return toAjax(fOutboundService.insertFOutbound(fOutbound));
    }

    /**
     * 修改出库管理
     */
    @RequiresPermissions("financial:fOutbound:edit")
    @GetMapping("/edit/{outId}")
    public String edit(@PathVariable("outId") Long outId, ModelMap mmap)
    {
        FOutbound fOutbound = fOutboundService.selectFOutboundByOutId(outId);
        mmap.put("fOutbound", fOutbound);
        mmap.put("peopleNumber",renshu(getSysUser().getDeptId()));
        return prefix + "/edit";
    }

    /**
     * 修改保存出库管理
     */
    @RequiresPermissions("financial:fOutbound:edit")
    @Log(title = "出库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FOutbound fOutbound)
    {
        fOutbound.setUpdateBy(getLoginName());
        return toAjax(fOutboundService.updateFOutbound(fOutbound));
    }

    /**
     * 删除出库管理
     */
    @RequiresPermissions("financial:fOutbound:remove")
    @Log(title = "出库管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fOutboundService.deleteFOutboundByOutIds(ids));
    }

    /**
     * 详细出库
     */
    @RequiresPermissions("financial:fOutbound:detail")
    @GetMapping("/detail/{outId}")
    public String detail(@PathVariable("outId") Long outId, ModelMap mmap)
    {
        FOutbound fOutbound = fOutboundService.selectFOutboundByOutId(outId);
        mmap.put("fOutbound", fOutbound);
        return prefix + "/detail";
    }

    @RequiresPermissions("financial:fOutbound:shenpi")
    @GetMapping("/examine/{outId}")
    public String examine(@PathVariable("outId") Long outId, ModelMap mmap)
    {
        FOutbound fOutbound = fOutboundService.selectFOutboundByOutId(outId);
        mmap.put("fOutbound", fOutbound);
        return prefix + "/examine";
    }

    @RequiresPermissions("financial:fOutbound:shenpi")
    @Log(title = "出库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/examineSave")
    @ResponseBody
    public AjaxResult examineSave(FOutbound fOutbound) {
        FOutbound newFOutbound = new FOutbound();
        newFOutbound.setOutId(fOutbound.getOutId());
        newFOutbound.setExamineStatus(fOutbound.getExamineStatus());
        newFOutbound.setExamineRemark(fOutbound.getExamineRemark());
        newFOutbound.setExamineBy(getLoginName());

        return toAjax(fOutboundService.examine(newFOutbound));
    }

    @GetMapping("/selectAverageSunhao/{thingId}/{thingType}")
    @ResponseBody
    public AjaxResult selectAverageSunhao(@PathVariable("thingId") Long thingId,@PathVariable("thingType") String thingType) {
        FOutbound outbound = new FOutbound();
        outbound.setThingId(thingId);
        outbound.setThingType(thingType);
        outbound.setParams(new HashMap<>());
        String sunhao = fOutboundService.selectAverageSunhao(outbound);
        FThing fThing = fThingService.selectFThingByThingId(thingId);
        Map map = new HashMap();
        map.put("sunhao",sunhao);
        map.put("thingUnit",fThing.getThingUnit());
        return AjaxResult.success("查询成功",map);
    }

    @GetMapping("/kucunDetail/{deptId}/{postId}/{thingId}/{enterId}")
    public String kucunDetail(@PathVariable("deptId") Long deptId,@PathVariable("postId") Long postId,@PathVariable("thingId") Long thingId,@PathVariable("enterId") Long enterId, ModelMap mmap)
    {
        mmap.put("deptId", deptId);
        mmap.put("postId", postId);
        mmap.put("thingId", thingId);
        mmap.put("enterId", enterId);
        return prefix + "/kucunDetail";
    }

    /**
     * 查询出库管理列表
     */
    @PostMapping("/kucunDetail/{deptId}/{postId}/{thingId}/{enterId}")
    @ResponseBody
    public TableDataInfo kucunDetail(@PathVariable("deptId") Long deptId,@PathVariable("postId") Long postId,@PathVariable("thingId") Long thingId,@PathVariable("enterId") Long enterId)
    {
        FEnter enter = fEnterService.selectFEnterByEnterId(enterId);

        FOutbound outbound = new FOutbound();
        outbound.setDeptId(deptId);
        outbound.setThingId(thingId);
        outbound.setThingId(enter.getThingId());
        outbound.setMohu(enter.getMohu());
        startPage();
        List<FOutbound> list = fOutboundService.selectFOutboundList(outbound);
        return getDataTable(list);
    }

//    //出库的，是否有库存
//    @GetMapping("/ischukucun/{thingId}/{thingType}")
//    @ResponseBody
//    public AjaxResult ischukucun(@PathVariable("thingId") Long thingId,@PathVariable("thingType") String thingType) {
//        String chushuliang = fOutboundService.selectShuliangByThingId(thingId, getSysUser().getDeptId(),thingType);
//        String rushuliang = fEnterService.selectShuliangByThingId(thingId, getSysUser().getDeptId(),thingType);
//        if(rushuliang == null ){
//            return AjaxResult.success("查询成功","0");
//        }
//
//        if(chushuliang == null){
//            return AjaxResult.success("查询成功",rushuliang.replaceAll("\\.0",""));
//        }
//
//        chushuliang = chushuliang.replaceAll("\\.0","");
//        rushuliang = rushuliang.replaceAll("\\.0","");
//
//        int chu = Integer.parseInt(chushuliang);
//        int ru = Integer.parseInt(rushuliang);
//
//        return AjaxResult.success("查询成功",ru-chu);
//    }


}
